<?php
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;

/**
 * 单位信息管理
 * Class RepairController
 * @package Admin\Controller
 */
class RepairController extends BaseController {
    /**
     * 系统管理 -> 系统管理 -> 建筑物信息维护 -> listview
     */
    public function index(){
        //获取搜索条件
        $filter = $this->fn_GenerateFilter();
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();

        //分页信息
        $pageNum = intval(I("post.page"));
        $pageNum = $pageNum==0?1:$pageNum;
        $page = $this->fn_GetPageInfo($where, $pageNum);
        $this->assign("page", $page);

        //搜索出小区信息
        $limit = ($page['from']-1).",".$page['num'];
        $list = M("repair")->where($where)->order($order)->limit($limit)->select();
        for($i=0; $i<count($list); $i++){
            $list[$i]["offset"] = $page['from']-1+$i;
        }
        $this->assign("list", $list);

        //设置community信息
        $this->assign("community", $this->fn_GetCommunityDict());

        //设置搜索条件
        $this->assign("filter", $filter);

        $this->display();
    }

    private function fn_GetCommunityList(){
        $where = array();
        if(self::$u["role_code"]=='20000'){ //小区管理员
            $com = $this->fn_GetCommunity(self::$u['username']);
            $where['id'] = array("in", $com);
        }
        return M("community")->where($where)->select();
    }

    private function fn_GetCommunityDict(){
        $where = array();
        if(self::$u["role_code"]=='20000'){ //小区管理员
            $com = $this->fn_GetCommunity(self::$u['username']);
            $where['id'] = array("in", $com);
        }

        $community = array();
        $list = M("community")->where($where)->select();
        for($i=0; $i<count($list); $i++){
            $community[$list[$i]["id"]] = $list[$i]["name"];
        }
        return $community;
    }

    /**
     * 建筑物信息维护 -> formview
     */
    public function detail(){
        //读取单位信息
        $dataId = I("get.id");
        $repair = M("repair")->where(array("id"=>$dataId))->find();
        $this->assign("repair", $repair);

        //查询条件
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $pageInfo = $this->fn_GetPageInfo($where);

        //页面信息
        $offset = intval(I("get.offset"));
        $nearby = $this->fn_FindNearbyItems($where, $order, $offset);
        $page = array_merge($pageInfo, $nearby);
        $this->assign("page", $page);

        // 设置上下文信息
        $context = $this->fn_GenerateContext($page);
        $this->assign("context", $context);

        //设置community信息
        $options = array(array("id"=>"等待维修","name"=>"等待维修"), array("id"=>"维修完成","name"=>"维修完成"));
        $this->assign("options", json_encode ($options));
        $community = $this->fn_GetCommunityDict();
        $this->assign("community", $community);
        $this->assign("opinion", $this->fn_GetOpinionList());
        $this->assign("log", $this->fn_GetSpLog($repair['no']));

        $this->display();
    }

    //获取维修单的审批日志
    private function fn_GetSpLog($repair_no){
        return M("repair_log")->where(array("repair_no"=>$repair_no))->select();
    }

    protected function fn_GetOpinionList(){
        return M("opinion")->where()->order("seq asc")->select();
    }

    /**
     * 建筑物信息维护 -> 新增
     */
    public function add(){  //todo
        if(IS_POST){    //添加小区信息
            $house = array("id"=>null, "name"=>null);
            if(I("post.house_addr")){
                $house = M("house")->where(array("addr"=>I("post.house_addr")))->find();
                if(!$house){
                    $this->error("操作失败，没有找到房源信息");
                }
            }
            $data = array(
                "no" => $this->fn_GenerateRepairNo(),
                "community_id" => I("post.community_id"),
                "house_addr" => I("post.house_addr"),
                "house_id" => $house["id"],
                "house_name" => $house["name"],
                "bxr" => I("post.bxr"),
                "bxdh" => I("post.bxdh"),
                "bxrq" => I("post.bxrq"),
                "bxms" => I("post.bxms"),
                "type" => I("post.type"),
                "xc1_Img" => I("post.xc1_Img"),
                "xc2_Img" => I("post.xc2_Img"),
                "xc3_Img" => I("post.xc3_Img"),
                "xc4_Img" => I("post.xc4_Img"),
                "remarks" => I("post.remarks"),
                "cuser" => session("username")
            );
            $dataId = M("repair")->add($data);
            if(!$dataId){
                $this->error("系统错误，创建维修单失败");
            }

            //给系统管理员发送通知
            $where = array("r.code"=>"10000");
            $user = M("user u")
                ->field("u.username")
                ->where($where)
                ->join(C('DB_PREFIX')."role r on r.id=u.role_id")
                ->select();

            $community = M("community")->where(array("id"=>$data['community_id']))->find();
            foreach($user as $item){
                $name = session("username")."提交了新的维修单";
                $r = $this->fn_SendNotice($item['username'], $name, $community['name'], $dataId);
                if(!$r){
                    $this->error("系统错误，发送系统消息失败");
                }
            }
            //跳转
            header("Location:/admin/repair/detail?id=".$dataId);
        }

        //复制信息时处理流程
        if(I("get.id") && I("get.action"=="copy")){
            $house = M("repair")->where(array("id"=>I("get.id")))->find();
            $this->assign("repair", $house);
        }

        //设置community信息
        $this->assign("community", $this->fn_GetCommunityList());
        $this->display();
    }

    private function fn_SendNotice($ruser, $name, $community_id, $rid){
        $data = array(
            "name"=>$name,
            "community"=>$community_id,
            "link"=>"/admin/repair/detail?id=".$rid,
            "cuser"=>session("username"),
            "ctime"=>date("Y/m/d"),
            "state"=>"未读",
            "ruser"=>$ruser
        );
        return M("notice")->add($data);
    }

    /**
     * 维修受理
     */
    public function ajax_accept(){
        $dataId = I("post.id");
        if(!$dataId){
            $this->error("缺少必要参数");
        }

        $trans = M();
        $trans->startTrans();   // 开启事务
        try{
            $repair = M("repair")->where(array("id"=>$dataId))->find();
            if(!$repair){
                $this->error("参数错误，没有找到对应的维修单");
            }
            //第一步：写入审批日志
            $data = array(
                "repair_no" => $repair['no'],
                "step" => "维修单受理",
                "state" => I("post.spzt"),
                "opinion" => I("post.spyj"),
                "cuser" => session("username"),
                "ctime" => date("Y/m/d"),
            );
            $res = M("repair_log")->add($data);
            if(!$res){
                $this->error("操作失败，写入维修日志失败");
            }

            //第二步：修改维修单状态
            $info = array("wxzt"=>"待现场勘察", "utime"=>time());
            $res = M("repair")->where(array("id"=>$dataId))->save($info);
            if(!$res){
                $this->error("操作失败，更新维修信息失败");
            }
            $trans->commit();   // 提交事务

        }catch (Exception $e){
            $trans->rollback();   // 开启事务
            $this->error($e->getMessage());
        }
        $this->success("操作成功");
    }

    public function ajax_draft(){
        $dataId = I("post.id");
        if(!$dataId){
            $this->error("缺少必要参数");
        }
        $trans = M();
        $trans->startTrans();   // 开启事务
        try{
            $repair = M("repair")->where(array("id"=>$dataId))->find();
            if(!$repair){
                $this->error("参数错误，没有找到对应的维修单");
            }
            //第一步：写入勘查数据
            $data = array(
                "wxzt" => "已作废",
                "utime" => time(),
            );
            $res = M("repair")->where(array("id"=>$dataId))->save($data);
            if(!$res){
                $this->error("操作失败，更新维修信息失败");
            }
            $trans->commit();   // 提交事务

        }catch (Exception $e){
            $trans->rollback();   // 开启事务
            $this->error($e->getMessage());
        }
        $this->success("操作成功");
    }

    /**
     * 录入勘察数据
     */
    public function ajax_survey(){
        $dataId = I("post.id");
        if(!$dataId){
            $this->error("缺少必要参数");
        }

        $trans = M();
        $trans->startTrans();   // 开启事务
        try{
            $repair = M("repair")->where(array("id"=>$dataId))->find();
            if(!$repair){
                $this->error("参数错误，没有找到对应的维修单");
            }
            //第一步：写入勘查数据
            $data = array(
                "wxzt" => "待审批",
                "survey" => I("post.survey"),
                "survey_ren" => I("post.survey_ren"),
                "kc1_Img" => I("post.kc1_Img"),
                "kc2_Img" => I("post.kc2_Img"),
                "kc3_Img" => I("post.kc3_Img"),
                "kc4_Img" => I("post.kc4_Img"),
                "survey_gq" => I("post.yjgq"),
                "survey_total" => I("post.wxys"),
                "utime" => time(),
            );
            $res = M("repair")->where(array("id"=>$dataId))->save($data);
            if(!$res){
                $this->error("操作失败，更新维修信息失败");
            }
            $trans->commit();   // 提交事务

        }catch (Exception $e){
            $trans->rollback();   // 开启事务
            $this->error($e->getMessage());
        }
        $this->success("操作成功");
    }

    /**
     * 审批
     */
    public function ajax_approve(){
        $dataId = I("post.id");
        if(!$dataId){
            $this->error("缺少必要参数");
        }

        $trans = M();
        $trans->startTrans();   // 开启事务
        try{
            $repair = M("repair")->where(array("id"=>$dataId))->find();
            if(!$repair){
                $this->error("参数错误，没有找到对应的维修单");
            }
            //第一步：写入审批日志
            $data = array(
                "repair_no" => $repair['no'],
                "step" => "维修审批",
                "state" => I("post.spzt"),
                "opinion" => I("post.spyj"),
                "cuser" => session("username"),
                "ctime" => date("Y/m/d"),
            );
            $res = M("repair_log")->add($data);
            if(!$res){
                $this->error("操作失败，写入维修日志失败");
            }

            //第二步：修改维修单状态
            $info = array("wxzt"=>"待验收", "utime"=>time());
            $res = M("repair")->where(array("id"=>$dataId))->save($info);
            if(!$res){
                $this->error("操作失败，更新维修信息失败");
            }
            $trans->commit();   // 提交事务

        }catch (Exception $e){
            $trans->rollback();   // 开启事务
            $this->error($e->getMessage());
        }
        $this->success("操作成功");
    }

    public function ajax_yanshou(){
        $dataId = I("post.id");
        if(!$dataId){
            $this->error("缺少必要参数");
        }

        $trans = M();
        $trans->startTrans();   // 开启事务
        try{
            $repair = M("repair")->where(array("id"=>$dataId))->find();
            if(!$repair){
                $this->error("参数错误，没有找到对应的维修单");
            }
            //第一步：写入审批日志
            $data = array(
                "repair_no" => $repair['no'],
                "step" => "维修验收",
                "state" => I("post.spzt"),
                "opinion" => "验收通过",
                "cuser" => session("username"),
                "ctime" => date("Y/m/d"),
            );
            $res = M("repair_log")->add($data);
            if(!$res){
                $this->error("操作失败，写入维修日志失败");
            }

            //第二步：修改维修单状态
            $info = array(
                "yanshou_rgf" => I("post.rgf"),
                "yanshou_clf" => I("post.clf"),
                "yanshou_qtf" => I("post.qtf"),
                "yanshou_sgdw" => I("post.sgdw"),
                "yanshou_sgdwdh" => I("post.sgdwdh"),
                "yanshou_fdate" => I("post.jgrq"),
                "yanshou_total" => I("post.rgf")+I("post.clf")+I("post.qtf"),
                "wxzt"=>"维修完成",
                "utime"=>time()
            );
            $res = M("repair")->where(array("id"=>$dataId))->save($info);
            if(!$res){
                $this->error("操作失败，更新维修信息失败");
            }
            $trans->commit();   // 提交事务

        }catch (Exception $e){
            $trans->rollback();   // 开启事务
            $this->error($e->getMessage());
        }
        $this->success("操作成功");
    }

    /**
     * 房屋自动补全搜索算法
     */
    public function ajax_SearchHouseByName(){
        $h = array();
        $where = array("community_id"=>I("get.community_id"),"addr"=>array("like", "%".I("get.house")."%"));
        $house = M("house")->where($where)->select();
        //$this->error(M("house")->getLastSql());
        foreach ($house as $v){
            array_push($h, array("value"=>$v["addr"], "data"=>$v));
        }
        $this->ajaxReturn(array('query'=>I("get.house"),'suggestions' => $h));
    }

    protected function fn_GenerateRepairNo(){
        $data = array("time"=>date("Y-m-d H:i:s"));
        $no = M("repair_no")->add($data);
        return "WX".$no;
    }

    /**
     * AJAX方法，在listview中进行批量删除信息
     */
    public function ajax_del(){

        $dataIds = I("post.info");
        if(count($dataIds)==0){
            $this->error("您还没有选中任何记录");
        }

        $map["id"] = array("in", $dataIds);
        $ma['wxzt'] = '等待受理';
        $res = M("repair")->where($map)->delete();
        if($res){
            $this->success("操作成功");
        }else{
            $this->error("系统错误");
        }
    }

    /**
     * AJAX方法，在formview中进行单条信息删除
     */
    public function ajax_del2(){
        //根据ID删除单位记录
        $id = I("post.id");
        $repair = M("repair")->where(array("id" => $id, "wxzt"=>'等待维修'))->find();
        if(!$repair){
            $this->error("操作失败，禁止删除");
        }

        $res = M("repair")->where(array("id" => $id))->delete();
        if(!$res){
            $this->error("系统错误");
        }

        //分页信息
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $total = $this->fn_GetTotalItems($where);
        if($total==0){
            $this->success(null);
        }

        //计算下一条记录的offset
        $offset = intval(I("post.offset"));
        $offset = ($offset>=$total-1)?0:$offset;

        //获取下一记录的信息
        $nextItem = $this->fn_GetInfoByOffset($offset, $where, $order);
        $this->success($nextItem["id"]); //返回下一条记录的ID
    }

    /**
     * AJAX方法，通过ID来修改信息
     */
    public function ajax_UpdateInfoById(){
        $data = I("post.data");
        $dataId = I("post.id");
        $res = M("repair")->where(array("id"=>$dataId))->save($data);
        if($res){
            $this->success("0k, 200");
        }else{
            $this->error("更新异常，请稍候再试");
        }
    }

    protected function fn_GetCommunity($username){
        $data = array();
        $where = array("admin_name"=>$username);
        $comm = M("community")->field("id")->where($where)->select();
        foreach ($comm as $item) {
            $data[] = $item['id'];
        }
        return $data;
    }

    /**
     *  辅助方法，通过$_POST的值来生成where查询条件
     */
    private function fn_GenerateWhereClause(){
        $where = array();
        if(self::$u["role_code"]=='20000'){ //小区管理员
            $com = $this->fn_GetCommunity(self::$u['username']);
            $where['community_id'] = array("in", $com);
        }

        if(I("request.value")){
            $where = array();
            if(I("request.field")=="community_id"){ //多表查询处理
                $cateIds = $this->fn_SelectCommunityByName(I("request.value"));
                $where[I("request.field")] = array("in", $cateIds);
            }else{
                $where[I("request.field")] = array("like", "%".I("request.value")."%");
            }
        }
        return $where;
    }

    private function fn_SelectCommunityByName($name){
        $where["name"] =  array("like", "%".$name."%");
        $result = M("community")->where($where)->field("id")->select();
        $cateIds = array();
        for($i=0; $i<count($result); $i++){
            array_push($cateIds, $result[$i]["id"]);
        }
        return $cateIds;
    }

    /**
     *  辅助方法，通过$_POST的值来生成order by子句
     */
    private function fn_GenerateOrderBy(){
        $order = "id desc";
        if(I("request.order_field") && I("request.order_sort")){
            $order = I("request.order_field") . " " . I("request.order_sort");
        }
        return $order;
    }

    /**
     *  辅助方法，通过$_POST的值来生成Filter (listview)
     */
    private function fn_GenerateFilter(){
        if(IS_POST){
            return array(
                "page" => I("post.page"),
                "field" => I("post.field"),
                "value" => I("post.value"),
                "order_field" => I("post.order_field"),
                "order_sort" => I("post.order_sort"),
            );
        }
        return array(
            "page" => 1,
            "order_field" => "id",
            "order_sort" => "desc",
        );
    }

    /**
     * 辅助方法，通过$_POST的值来生成Context (formvier)
     * @return array
     */
    private function fn_GenerateContext($page){
        return array(
            "id" => I("request.id"),
            "field" => I("request.field"),
            "value" => I("request.value"),
            "order_field" => I("request.order_field"),
            "order_sort" => I("request.order_sort"),
            "page" => I("request.page"),
            "offset" => I("request.offset"),
            "index" => I("get.offset")-($page["curPage"]-1)*$page["num"]+1
        );
    }

    /**
     * 辅助方法，通过where,order,offset来查询信息
     * @param $offset
     * @param $where
     * @param $order
     * @return mixed
     */
    private function fn_GetInfoByOffset($offset, $where, $order){
        $limit = $offset.",1";
        $res =  M("repair")->field("id,name")->where($where)->order($order)->limit($limit)->select();
        if($res){
            return $res[0];
        }
        return array();
    }

    /**
     * 辅助方法，通过where, curpage, num来生成分页信息
     * @param $where
     * @param int $curPage
     * @param int $num
     * @return array
     */
    private function fn_GetPageInfo($where, $curPage=1, $num=15){
        $total = M("repair")->where($where)->count();
        $totalPage = ceil($total/$num);
        $nextPage = $curPage==$totalPage?1:($curPage+1);
        $prevPage = $curPage==1?$totalPage:($curPage-1);
        $to = $curPage*$num;
        $res = array(
            "total" => $total,
            "num" => $num,
            "from" => (($curPage-1)*$num+1),
            "to" => $to>$total?$total:$to,
            "curPage" => $curPage,
            "nextPage" => $nextPage,
            "prevPage" => $prevPage
        );
        return $res;
    }

    /**
     * 辅助方法，通过where来统计总的信息数量
     * @param array $where
     * @return mixed
     */
    public function fn_GetTotalItems($where=array()){
        return M("repair")->where($where)->count();
    }

    /**
     * 辅助方法，通过where, order, offset查询相邻两条数据
     * @param $where
     * @param $offset
     */
    public function fn_FindNearbyItems($where, $order, $offset){
        $total = M("repair")->where($where)->count();
        $prevOffset = $offset>0?$offset-1:$total-1;
        $nextOffset = $offset>=$total-1?0:$offset+1;
        $prevItem = $this->fn_GetInfoByOffset($prevOffset, $where, $order);
        $nextItem = $this->fn_GetInfoByOffset($nextOffset, $where, $order);
        return array(
            "prev" => array("id"=>$prevItem["id"],"offset"=>$prevOffset),
            "next" => array("id"=>$nextItem["id"],"offset"=>$nextOffset),
        );
    }

}